package com.ricervcvcer.brand.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ricervcvcer.brand.entity.TbBrand;
import com.ricervcvcer.brand.entity.TbCategoryBrand;
import com.ricervcvcer.brand.mapper.TbBrandMapper;
import com.ricervcvcer.brand.service.ITbBrandService;
import com.ricervcvcer.brand.service.ITbCategoryBrandService;
import com.ricervcvcer.brand.util.GetPingYin;
import com.ricervcvcer.brand.vo.BrandCategoryVo;
import com.ricervcvcer.common.util.RicervcvcerConstant;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 品牌表，一个品牌下有多个商品（spu），一对多关系 服务实现类
 * </p>
 *
 * @author moge
 * @since 2022-01-05
 */
@Service
public class TbBrandServiceImpl extends ServiceImpl<TbBrandMapper, TbBrand> implements ITbBrandService {

    @Resource
    TbBrandMapper brandMapper;
    @Autowired
    ITbCategoryBrandService categoryBrandService;

    @Override
    public Page<TbBrand> getBrand(String brandName, Integer page, Integer rows) {
        Page<TbBrand> brandPage = new Page<>(page, rows);
        QueryWrapper<TbBrand> qw=new QueryWrapper();
        if(!"".equals(brandName)){
            qw.eq("name",brandName).or().eq("letter",brandName);
        }
        brandPage = brandMapper.selectPage(brandPage,qw);
        return brandPage;
    }

    @Transactional
    @Override
    public void add(BrandCategoryVo bc) {
        QueryWrapper qw=new QueryWrapper();
        qw.eq("name",bc.getName());
        TbBrand one = this.getOne(qw);
        if(!Objects.isNull(one)){
            throw  new RuntimeException("已经存在这个品牌");
        }
        // 设置首字母大写
        final String letter = GetPingYin.getPinYinHeadChar(bc.getName()).toUpperCase().substring(0, 1);
        bc.setLetter(letter);

        // 分装品牌对象
        TbBrand tbBrand=new TbBrand();
        BeanUtils.copyProperties(bc,tbBrand);

        // 添加品牌
        final boolean brandStatus = this.save(tbBrand);

        // 添加品牌分类关联表
        List<TbCategoryBrand> collect = getTbCategoryBrands(bc, tbBrand);

        // 批量添加
        boolean tcbStatus = categoryBrandService.saveBatch(collect);

        if(!(brandStatus && tcbStatus)){
            throw new RuntimeException(RicervcvcerConstant.ADD_ERROR);
        }
    }

    @Transactional
    @Override
    public void updateBrand(BrandCategoryVo bc) {
        // 提取对象
        TbBrand brand = new TbBrand();
        BeanUtils.copyProperties(bc,brand);

        final boolean b = this.updateById(bc);

        // 添加的分类
       if ((!Objects.isNull(bc.getCategories())) && bc.getCategories().size()>0){
           // 判断分类是否重复添加
           // 1，获取已经添加的分类集合2
           QueryWrapper qw=new QueryWrapper();
           qw.eq("brand_id",brand.getId());
           List<TbCategoryBrand> list = categoryBrandService.list(qw);

           // 2，循环判断是否已经添加分类
           // 2。1，获取即将 添加的分类集合2
           final List<Long> categoryIds = bc.getCategories();

           // 分装所有已经添加的分类
           List<Long> cids=new ArrayList<>();
           for (TbCategoryBrand categoryBrand : list){
               cids.add(categoryBrand.getCategoryId());
           }

           // 进行过滤
           List<Long> collect = categoryIds.stream().filter(item -> {
               return !cids.contains(item);
           }).collect(Collectors.toList());
           bc.setCategories(collect);

           // 关联分类对象
           List<TbCategoryBrand> tcbs = bc.getCategories().stream().map(item -> {
               TbCategoryBrand tcb = new TbCategoryBrand();
               tcb.setBrandId(brand.getId());
               // 数组下标2为三级ID
               tcb.setCategoryId(item);
               return tcb;
           }).collect(Collectors.toList());
           // 批量添加分类关联表
           if(collect.size()>0) {
               boolean tcbStatus = categoryBrandService.saveBatch(tcbs);
               if (!(tcbStatus)) {
                   throw new RuntimeException(RicervcvcerConstant.UPDATE_ERROR);
               }
           }
       }

        if(!(b)){
            throw new RuntimeException(RicervcvcerConstant.UPDATE_ERROR);
        }
    }

    /**
     * 获取与之关联的分类对象集合
     * @param bc
     * @param tbBrand
     * @return
     */
    private List<TbCategoryBrand> getTbCategoryBrands(BrandCategoryVo bc, TbBrand tbBrand) {
        List<TbCategoryBrand> collect = bc.getCategoryIds().stream().map(item -> {
            TbCategoryBrand tcb = new TbCategoryBrand();
            tcb.setBrandId(tbBrand.getId());
            // 数组下标2为三级ID
            tcb.setCategoryId(item[2]);
            return tcb;
        }).collect(Collectors.toList());
        return collect;
    }
}
